package com.lbc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.lbc.bean.entity.Donate;
import com.lbc.bean.vo.DonateRecordVO;
import com.lbc.bean.vo.DonateStatisticsVO;
import com.lbc.common.constants.AliPayConstants;
import com.lbc.common.utils.JwtUtils;
import com.lbc.dao.custom.CtDonateMapper;
import com.lbc.dao.custom.CtDonateProjectMapper;
import com.lbc.dao.custom.CtUserMapper;
import com.lbc.service.DonateService;
import com.lbc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xyl
 * @date 2021-03-19 20:21
 */
@Service
public class DonateServiceImpl implements DonateService {

    @Autowired
    private CtDonateMapper donateMapper;
    @Autowired
    private CtDonateProjectMapper donateProjectMapper;
    @Autowired
    private CtUserMapper userMapper;

    @Override
    public Object toDonate(Integer projectId, Float money,String str) {
        String bh = System.currentTimeMillis() + "";
        Donate donate = new Donate();
        donate.setCreateBy(JwtUtils.getUserId());
        donate.setCreateTime(new Date());
        donate.setDonateBy(userMapper.selectByPrimaryKey(JwtUtils.getUserId()).getUsername());
        donate.setDonateTo(projectId);
        //未支付成功
        donate.setState(0);
        //0是项目
        if("kid".equalsIgnoreCase(str)){
            donate.setType(1);
        }else{
            donate.setType(0);
        }
        donate.setNumber(bh);
        donate.setMoney(money);
        donateMapper.insert(donate);
        return this.donate(bh,money);
    }


    @Override
    public int notifyDonate(String number) {

        return donateMapper.updateStateByNumber(1,number);
    }

    @Override
    public DonateStatisticsVO getDonateStatistics() {
        DonateStatisticsVO donateStatisticsVO = donateMapper.selectDonateStatistics();
        donateStatisticsVO.setDonateProjectTotalCount(donateProjectMapper.selectCount());
        return donateStatisticsVO;
    }

    @Override
    public List<DonateRecordVO> getDonateRecord() {
        Integer userId = JwtUtils.getUserId();
        return donateMapper.selectDonateRecord(userId);
    }


    private String donate(String bh, float totalMoney) {
        // 构建支付数据信息
        Map<String, String> data = new HashMap<>();
        //订单标题
        data.put("subject", "请进行支付");
        //商户订单号,64个字符以内、可包含字母、数字、下划线；需保证在商户端不重复
        data.put("out_trade_no", bh);
        //该笔订单允许的最晚付款时间
        data.put("timeout_express", "1h");
        //订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]
        data.put("total_amount", new DecimalFormat(".00").format(totalMoney) + "");
        //销售产品码，商家和支付宝签约的产品码，为固定值QUICK_MSECURITY_PAY
        data.put("product_code", "FAST_INSTANT_TRADE_PAY");
        //构建客户端
        DefaultAlipayClient alipayRsa2Client = new DefaultAlipayClient(
                AliPayConstants.gatewayUrl,
                AliPayConstants.app_id,
                AliPayConstants.merchant_private_key,
                "json",
                AliPayConstants.charset,
                AliPayConstants.alipay_public_key,
                AliPayConstants.sign_type);
        /*APP支付*/
//        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        /*网页支付*/
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        /*移动h5*/
//        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
//        request.setNotifyUrl(AliPayConstants.ALI_NOTIFY_URL);
        request.setReturnUrl(AliPayConstants.ALI_NOTIFY_URL);
        request.setBizContent(JSON.toJSONString(data));
        String response = null;
        try {
            response = alipayRsa2Client.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return response;
    }
}
